<?php

namespace Frontend\Forms;

use DuAdmin\Helpers\MailHelper;
use Yii;
use yii\base\Model;
use Frontend\Models\User;

/**
 * Password reset request form
 */
class PasswordResetRequestForm extends Model
{
    public $email;

    public $captcha;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            [
                'email', 'exist',
                'targetClass' => User::class,
                'filter' => ['status' => [User::STATUS_ACTIVE, User::STATUS_INACTIVE]],
                'message' => 'There is no user with this email address.'
            ],
            ['captcha', 'trim'],
            ['captcha', 'required'],
            [
                'captcha',
                'captcha'
            ]
        ];
    }

    public function attributeLabels()
    {
        return [
            'email' => Yii::t('app_user', 'Email'),
            'captcha' => Yii::t('app_user', 'Captcha'),
        ];
    }

    /**
     * Sends an email with a link, for resetting the password.
     *
     * @return bool whether the email was send
     */
    public function sendEmail()
    {
        /* @var $user User */
        $user = User::findOne([
            'status' => [User::STATUS_ACTIVE, User::STATUS_INACTIVE],
            'email' => $this->email,
        ]);

        if (!$user) {
            return false;
        }

        if (!User::isPasswordResetTokenValid($user->passwordResetToken)) {
            $user->generatePasswordResetToken();
            if (!$user->save()) {
                return false;
            }
        }
        $template = MailHelper::getMailContent('sys_reset_password_mail', [
            '{username}' => $user->username,
            '{resetLink}' => Yii::$app->urlManager->createAbsoluteUrl([
                '/forget-password/reset',
                'token' => $user->passwordResetToken
            ])
        ]);

        return MailHelper::sendEmail(
            [getenv('MAIL_USERNAME') => getenv('MAIL_ALIAS')],
            $user->email,
            $template['title'],
            $template['content']
        );
    }
}
